/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.dingmouren.layoutmanagergroup.sample.adapter;

import com.ohos.RecyclerContainer;
import com.dingmouren.layoutmanagergroup.sample.ResourceTable;
import com.dingmouren.layoutmanagergroup.utils.LogUtil;
import com.openharmony.recyclercomponent.ContainerGroup;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.Component;
import ohos.agp.components.Image;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.Text;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.Color;
import ohos.global.resource.NotExistException;
import ohos.global.resource.Resource;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.media.image.common.PixelFormat;
import ohos.media.image.common.Rect;
import ohos.media.image.common.Size;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * Function description
 * class AdapterOriginal
 */
public class EchelonAdapter extends RecyclerContainer.Adapter {
    private String[] nickNames = {"左耳近心", "凉雨初夏", "稚久九栀", "半窗疏影"};
    private String[] descs = {
            "回不去的地方叫故乡 没有根的迁徙叫流浪...",
            "人生就像迷宫，我们用上半生找寻入口，用下半生找寻出口",
            "原来地久天长，只是误会一场",
            "不是故事的结局不够好，而是我们对故事的要求过多",
            "只想优雅转身，不料华丽撞墙"
    };

    public EchelonAdapter() {
    }

    @Override
    public RecyclerContainer.ViewHolder createViewHolder(ContainerGroup parent, int viewType) {
        return new EchelonViewHolder(LayoutScatter.getInstance(parent.getContext())
                .parse(ResourceTable.Layout_item_echelon, null, false));
    }

    @Override
    public void bindViewHolder(RecyclerContainer.ViewHolder holder, int position) {
        EchelonViewHolder echelonViewHolder = null;
        if (holder instanceof EchelonViewHolder) {
            echelonViewHolder = (EchelonViewHolder) holder;
        }
        assert echelonViewHolder != null;
        int background, header;
        switch (position % 4) {
            case 0:
                background = ResourceTable.Graphic_tree;
                header = ResourceTable.Media_header_icon_1;
                break;
            case 1:
                background = ResourceTable.Graphic_tree1;
                header = ResourceTable.Media_header_icon_2;
                break;
            case 2:
                background = ResourceTable.Graphic_tree2;
                header = ResourceTable.Media_header_icon_3;
                break;
            case 3:
                background = ResourceTable.Graphic_tree3;
                header = ResourceTable.Media_header_icon_4;
                break;
            default:
                background = ResourceTable.Graphic_tree6;
                header = ResourceTable.Media_header_icon_1;
        }
        ShapeElement shapeElement = new ShapeElement();
        shapeElement.setRgbColor(RgbColor.fromArgbInt(Color.BLACK.getValue()));
        echelonViewHolder.itemView.setBackground(shapeElement);
        try {
            echelonViewHolder.ivBg.setPixelMap(preparePixelmap(echelonViewHolder.ivBg.getResourceManager()
                    .getResource(background)));
            echelonViewHolder.ivIcon.setPixelMap(preparePixelmap(echelonViewHolder.ivIcon.getResourceManager()
                    .getResource(header)));
            echelonViewHolder.tvNickName.setText(nickNames[position % 4]);
            echelonViewHolder.tvDesc.setText(descs[position % 5]);
        } catch (IOException | NotExistException e) {
            LogUtil.error("View", "" + e.getMessage());
        }
    }

    @Override
    public int getItemCount() {
        return 60;
    }

    static class EchelonViewHolder extends RecyclerContainer.ViewHolder {
        private Text tvNickName, tvDesc;
        private Image ivIcon, ivBg;

        EchelonViewHolder(Component itemView) {
            super(itemView);
            if (itemView.findComponentById(ResourceTable.Id_tv_nickname) instanceof Text) {
                tvNickName = (Text) itemView.findComponentById(ResourceTable.Id_tv_nickname);
            }
            if (itemView.findComponentById(ResourceTable.Id_tv_desc) instanceof Text) {
                tvDesc = (Text) itemView.findComponentById(ResourceTable.Id_tv_desc);
            }
            if (itemView.findComponentById(ResourceTable.Id_img_icon) instanceof Image) {
                ivIcon = (Image) itemView.findComponentById(ResourceTable.Id_img_icon);
            }
            if (itemView.findComponentById(ResourceTable.Id_img_bg) instanceof Image) {
                ivBg = (Image) itemView.findComponentById(ResourceTable.Id_img_bg);
            }
        }
    }

    private static PixelMap preparePixelmap(Resource resource) throws IOException {
        ImageSource.SourceOptions srcOpts = new ImageSource.SourceOptions();
        ImageSource imageSource;
        try {
            imageSource = ImageSource.create(readResource(resource), srcOpts);
        } finally {
            resource.close();
        }
        if (imageSource == null) {
            LogUtil.debug("File", "Not Found");
        }
        ImageSource.DecodingOptions decodingOpts = new ImageSource.DecodingOptions();
        decodingOpts.desiredSize = new Size(0, 0);
        decodingOpts.desiredRegion = new Rect(0, 0, 0, 0);
        decodingOpts.desiredPixelFormat = PixelFormat.ARGB_8888;

        return imageSource.createPixelmap(decodingOpts);
    }

    private static byte[] readResource(Resource resource) throws IOException {
        final int bufferSize = 1024;
        final int ioEnd = -1;

        ByteArrayOutputStream output = new ByteArrayOutputStream();
        byte[] buffer = new byte[bufferSize];
        while (true) {
            try {
                int readLen = resource.read(buffer, 0, bufferSize);
                if (readLen == ioEnd) {
                    break;
                }
                output.write(buffer, 0, readLen);
            } catch (IOException e) {
                break;
            } finally {
                output.close();
            }
        }

        return output.toByteArray();
    }
}